import configparser as ConfigParser
import os

from loguru import logger

from com.arcfox.util import constant, util


class Config:

    def __init__(self, file_name):
        self.cf = ConfigParser.ConfigParser()
        self.section = constant.DEFAULT_SPIDER_CONFIG_SECTION
        self.base_dir = util.get_parent_dir(os.path.dirname(os.path.realpath(__file__))) + os.sep + "config/"
        self.full_name = self.base_dir + file_name

    def get(self, key):
        self.cf.read(self.full_name)
        try:
            value = self.cf.get(self.section, key)
        except Exception as e:
            logger.exception(e)
            return None
        try:
            value = float(value)
        except:
            value = str(value)
        return value

    def set(self, key, value):
        self.cf.read(self.full_name)
        self.cf.set(self.section, key, str(value))
        self.cf.write(open(self.full_name, "w"))